package org.aplikator.client.shared.data;

import org.aplikator.client.shared.descriptor.ViewDTO;
import org.jboss.errai.common.client.api.annotations.Portable;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("serial")
@Portable
public class RecordContainer implements Serializable {

    private List<ContainerNode> nodes = new ArrayList<ContainerNode>();

    public RecordContainer() {
    }

    public void addRecord( ViewDTO view, Record original, Record edited, Operation operation) {
        boolean foundExisting = false;
        if (Operation.UPDATE.equals(operation)) {
            for (ContainerNode node : nodes) {
                if (original.getPrimaryKey().equals(node.getOriginal().getPrimaryKey())) {
                    if (Operation.UPDATE.equals(node.getOperation()) || Operation.CREATE.equals(node.getOperation())) {

                        node.setEdited(edited);
                        foundExisting = true;
                        break;
                    }
                }
            }
        }
        if (!foundExisting) {
            nodes.add(new ContainerNode(view != null ? view.getId() : null, original, edited, operation));
        }
    }

    public List<ContainerNode> getRecords() {
        return nodes;
    }

    public void setContainerNodes(List<ContainerNode> nodes) {
    	this.nodes = nodes;
    }
    
    public void clear() {
        nodes.clear();
    }

    
    public Record findLastUpdated(PrimaryKey primaryKey) {
        Record retval = null;
        for (ContainerNode node : nodes) {
            if (Operation.UPDATE.equals(node.getOperation())) {
                if (primaryKey.equals(node.getEdited().getPrimaryKey())) {
                    retval = node.getEdited();
                }
            }
        }
        return retval;
    }

}
